@echo off

title WELLCOMM

(netstat -anp TCP | findstr /E /C:"LISTENING" | findstr /B /C:"  TCP    127.0.0.1:443" >nul ^
|| netstat -anp TCP | findstr /E /C:"LISTENING" | findstr /B /C:"  TCP    0.0.0.0:443" >nul) && (
  echo port 443 is in using!
  echo It looks like the SSH tunnel is already opened
  echo or port 443 is used by other programs
  pause
  exit /b 1
)
  
set ORGDIR=%SystemRoot%\system32\drivers\etc
set BAKDIR=%TEMP%\system32\drivers\etc

findstr /R /C:"^### wellcomm.work ###$" "%ORGDIR%\hosts" >nul && (
  echo hosts file seems not be restored properly
  echo You need to check your hosts file and fix it before continue
  pause
  start /WAIT notepad "%ORGDIR%\hosts"
)

robocopy "%ORGDIR%" "%BAKDIR%" hosts /COPYALL 

echo ========BACKUP "%ORGDIR%\hosts"
type "%ORGDIR%\hosts"

(
echo ### wellcomm.work ###
echo ::1 gitea.wellcomm.work
echo ::1 zentao.wellcomm.work
echo 127.0.0.1 gitea.wellcomm.work
echo 127.0.0.1 zentao.wellcomm.work
echo.
type "%BAKDIR%\hosts"
) > "%ORGDIR%\hosts"

ssh sshtun@gate.wellcomm.work -p 10022 -vNTL 443:localhost:443 -o ExitOnForwardFailure=yes ^
  & robocopy "%BAKDIR%" "%ORGDIR%" hosts /COPYALL /MOVE